﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.IO;

namespace Prism.Core.Storage
{
    public static class Extension
    {
        public static void AddData(
            this DifferentialDataList dataList,
            string accessName,
            string groupName,
            Stream stream,
            DifferentialDataTable dataTable)
        {
            var data = new Data() { AccessName = accessName, GroupName = groupName };
            dataList.Add(data);
            var dataPath = Path.GetFullPath(groupName);
            FileStream fs;
            if (!File.Exists(dataPath))
                fs = new FileStream(dataPath, FileMode.Create);
            else fs = new FileStream(dataPath, FileMode.Append, FileAccess.Write);
            var length = (int)stream.Length;
            var totalDataLength = dataTable.GroupDataLength[groupName];
            data.StartPoint = totalDataLength + 1;
            data.EndPoint = data.StartPoint + length - 1;
            data.Length = length;
            var buffer = new byte[length];
            stream.Read(buffer, 0, length);
            fs.Write(buffer, 0, length);
            fs.Close();
            totalDataLength = data.EndPoint;
            dataTable.GroupDataLength[groupName] = totalDataLength;
        }

        public static Stream GetData(this Data data, string root)
        {
            var length = (int)data.Length;
            var dataPath = string.Empty;
            if (root == string.Empty)
                dataPath = Path.GetFullPath(data.GroupName);
            else
                dataPath = Path.Combine(root, data.GroupName);
            var fs = new FileStream(dataPath, FileMode.Open);
            var ms = new MemoryStream();
            var buffer = new byte[length];
            fs.Position = data.StartPoint;
            fs.Read(buffer, 0, length);
            ms.Write(buffer, 0, length);
            fs.Close();
            ms.Position = 0;
            return ms;
        }
    }
}
